import logIt from 'log_it';
import { showModal } from './wxApis';

const log = logIt('@openSetting');

/**
 * 打开设置
 * @param  {Object|String} [options]    弹窗配置, 如果没有设定，则直接打开设置
 */
async function openSetting(options, mustAuthName) {
  return new Promise((async (resolve, reject) => {
    if (!wx.openSetting) {
      throw new Error('can not use wx.openSetting');
    }
    if (options) {
      const res = await showModal(options);
      if (res.cancel) {
        throw new Error('用户未去设置');
      }
    }

    wx.openSetting({
      success: ({ authSetting }) => {
        if (mustAuthName && !authSetting[`scope.${mustAuthName}`]) {
          reject(new Error('用户未打开开关'));
        }
        resolve(authSetting);
      },
      fail: ({ errMsg }) => reject(new Error(errMsg)),
    });
  }));
}

const authDenyReg = /^(\w+):fail[ :]auth deny$/;
const authInfos = {
  getUserInfo: {
    authName: 'userInfo',
    authText: '用户信息',
  },
  saveVideoToPhotosAlbum: {
    authName: 'saveVideoToPhotosAlbum',
    authText: '保存到本地',
  },
};
function getAuthFromAuthDenyMsg(msg) {
  const res = authDenyReg.exec(msg);
  if (!res) {
    return undefined;
  }
  log.info(res);
  return authInfos[res[1]];
}

function isAuthDenyMsg(msg) {
  return authDenyReg.test(msg);
}

async function autoOpenSettingWhenNeedAuth(cb, times = 1) {
  try {
    return await cb();
  } catch (error) {
    if (times <= 0) {
      throw error;
    }
    const authInfo = getAuthFromAuthDenyMsg(error.message);
    if (!authInfo) {
      throw error;
    }
    const { authText, authName } = authInfo;
    await openSetting({
      title: `未授权"${authText}"`,
      content: `打开"${authText}"权限`,
      confirmText: '去授权',
    }, authName);
    return autoOpenSettingWhenNeedAuth(cb, times - 1);
  }
}

export {
  isAuthDenyMsg,
  autoOpenSettingWhenNeedAuth,
};

export default openSetting;
